SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO

CREATE PROCEDURE [dbo].[DnnProduct_CDS_TemplatesAdd]
	@DistributorID varchar(50),
	@Name nvarchar(255),
	@Description ntext,
	@Default bit,
	@Type varchar(20)
AS
BEGIN
	IF (@Default = 1)
	BEGIN
		UPDATE [DnnProduct_CDS_Templates]
		SET [Default] = 0
		WHERE DistributorID = @DistributorID AND [Type] = @Type
	END
	ELSE IF NOT EXISTS(SELECT [ID] FROM [DnnProduct_CDS_Templates] WHERE DistributorID = @DistributorID AND [Type] = @Type)
	BEGIN
		SET @Default = 1
	END

	INSERT INTO [DnnProduct_CDS_Templates] (DistributorID, [Name], [Description], [Default], [Type])
	VALUES (@DistributorID, @Name, @Description, @Default, @Type)

	SELECT scope_identity()
END
GO
